package com.modular.extra.fm.factor.rule.opt;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.c.opt.ComOpt;
import com.c.opt.tool.ToolEntity;
import com.modular.extra.fm.FactoryFmOpt;
import com.modular.extra.fm.factor.rule.bean.FactoryRuleDo;
import com.tool.ToolRedisson;
import ntd.util.UtilCatch;
import ntd.util.frame.data.tool.ToolMysql;
import ntd.util.frame.task.handle.fm.bo.FmDataRecordRule;
import org.redisson.api.RList;

import java.time.Duration;
import java.util.List;

public class OptFactoryRule extends ComOpt<FactoryRuleDo> {

    public OptFactoryRule() {
        super("data_rule", FactoryFmOpt.DS_ID);
    }

    /**
     * 查询数据规则列表
     * @param mns
     * @return
     */
    public List<Entity> listDataRule(List<String> mns) {

        String key = StrUtil.subSufByLength(DigestUtil.sha256Hex(CollectionUtil.join(mns, ",")), 100);

        RList<Entity> list = ToolRedisson.me.redisson.getList(StrUtil.format("fm-site-data-rule-{}", key));
        if (list.isEmpty()) {
            String sql = "SELECT dr.rule_name, dr.id rule_id, dr.mn, dri.*, df.factor_name, df.factor_code FROM data_rule dr\n" +
                    "INNER JOIN data_rule_item dri ON dr.id = dri.rule_id " +
                    "INNER JOIN data_factor df ON dri.factor_id = df.id ";
            // 查询站点因子标准（超标标准信息）
            if (CollectionUtil.isNotEmpty(mns)) {
                sql += StrUtil.format(" WHERE dr.mn in {};", ToolMysql.listToSqlStr(mns));
            }
            String finalSql = sql;
            list.addAll(UtilCatch.tryCatch(() -> db().query(finalSql)));
            list.expire(Duration.ofSeconds(60 * 10));
        }
        return list;
    }

    public static void main(String[] args) {
        StaticLog.info(JSONUtil.toJsonStr(new OptFactoryRule().listDataRuleBo(ListUtil.of("F4107250100007"))));
//        for (int i = 0; i < 1000; i++) {
//
//        }
    }

    /**
     * 查询数据规则列表 - 业务对象
     * @param mns
     * @return
     */
    public List<FmDataRecordRule> listDataRuleBo(List<String> mns) {
        return CollStreamUtil.toList(listDataRule(mns), entity -> ToolEntity.toBean(entity, FmDataRecordRule.class));
    }

}
